<?php

namespace app\admin\controller;


use app\common\model\AppFaceModel;
use app\common\model\RegSourceModel;
use think\facade\Request;
use think\Db;


class AppfaceController extends BaseController
{

    public function index()
    {
        $source = Request::param("source");
        $this->assign('source', $source);
        return $this->fetch();
    }

    public function getlist()
    {
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $list = AppFaceModel::alias('t1') 
        ->field('t1.*, t2.source_name as default_channel_name, t3.source_name as new_channel_name') 
        ->leftJoin('db_reg_source t2', 't1.default_channel = t2.source_key') 
        ->leftJoin('db_reg_source t3', 't1.new_channel = t3.source_key') 
        ->page($page, $limit)
        ->order('id', 'desc')
        ->select();
        if (count($list) > 0) {
            $count = AppFaceModel::count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }
    /**
     * 添加页面
     * @return mixed
     */
    public function add()
    {
        if (Request::isAjax()) {
            $all_param = Request::param();
            $appface_model = new AppFaceModel($all_param);

            Db::startTrans();
            try {
                if (!$appface_model->save()) {
                    throw new \Exception('添加失败');
                }

                // 记录日志
                $log_content = "添加渠道信息对应，DEFAULT_CHANNEL：{$appface_model->default_channel}，new_channel：{$appface_model->new_channel}";
                parent::addAdminLog($log_content);

                Db::commit();
                return self::bulidSuccess();
            } catch (\Exception $e) {
                Db::rollback();
                echo $e->getMessage();
            }
            return self::bulidFail('添加失败');
        }
        $list = RegSourceModel::select();
        $this->assign("default_channel", $list);
        $this->assign("new_channel", $list);
        return $this->fetch();
    }

    public function del_post() {
        $id       = Request::param('id');
        $appface = AppFaceModel::get($id);
        if (!$appface) {
            return self::bulidFail('未查询到数据');
        }

        if (AppFaceModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除渠道映射, ID：{$appface->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}